package com.ashun.config;

import com.ashun.comm.RequiredToken;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by lvenle on 2017/6/6.
 * 在mywebappconfigurer中设置拦截连
 */
public class WebFilter implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
        System.out.println(httpServletRequest.getSession().getId());
        System.out.println(httpServletRequest.getHeader("Accept"));
        System.out.println(o.getClass());
        Class clazz = o.getClass();
        HandlerMethod handlerMethod = (HandlerMethod) o;
        System.out.println(handlerMethod.getMethod());
        Method method = null;
        method = handlerMethod.getMethod();
        MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
        for(MethodParameter methodParameter : methodParameters) {
            System.out.println(methodParameter.getParameterName());
            System.out.println(methodParameter.getParameterType());
        }
        // 获取切点方法跟该方法所在类的token注解 如果加的有token注解 取出值验证
        boolean requiredVal;
        if (method.isAnnotationPresent(RequiredToken.class)) {
            // 获取方法上的注解
            requiredVal = method.getAnnotation(RequiredToken.class).value();
        } else if (clazz.isAnnotationPresent(RequiredToken.class)) {
            // 获取切点方法所在类的注解
            requiredVal = ((RequiredToken) clazz.getAnnotation(RequiredToken.class)).value();
        } else {
            requiredVal = false;
        }
//        System.out.println(httpServletResponse.geth);
        return true;// 只有返回true才会继续向下执行，返回false取消当前请求
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }
}
